package com.huawo.opensdk;


import static androidx.appcompat.content.res.AppCompatResources.getDrawable;
import static com.huawo.opensdk.ApplicationHolder.sApplication;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;

import com.huawo.opensdk.bean.ConnectDevice;
import com.huawo.opensdk.bean.FirmwareVersionDate;
import com.huawo.opensdk.bean.QjsWatchFaceBean;
import com.huawo.opensdk.bean.VersionBean;
import com.huawo.opensdk.listener.OnWatchFaceTransListener;
import com.huawo.opensdk.manager.DeviceUpgradeManager;
import com.huawo.opensdk.utils.FirmwareVersionUtils;
import com.huawo.opensdk.utils.SM;
import com.huawo.qjs.QjsWatchface;
import com.huawo.qjs.QjsWidget;
import com.huawo.qjs.callback.QjsWatchfaceCallback;
import com.huawo.qjs.utils.ImageUtils;
import com.huawo.qjs.utils.SFSDK;
import com.huawo.qjs.widgets.QjsCalorie;
import com.huawo.qjs.widgets.QjsHeartrate;
import com.huawo.qjs.widgets.QjsStep;
import com.huawo.qjs.widgets.QjsTime;
import com.huawo.sdk.bluetoothsdk.BluetoothSDK;
import com.huawo.sdk.bluetoothsdk.callback.DisconnectCallback;
import com.huawo.sdk.bluetoothsdk.core.model.Device;
import com.huawo.sdk.bluetoothsdk.interfaces.callback.BoolCallback;
import com.huawo.sdk.bluetoothsdk.interfaces.callback.BoolValueCallback;
import com.huawo.sdk.bluetoothsdk.interfaces.callback.CreateBondCallback;
import com.huawo.sdk.bluetoothsdk.interfaces.callback.IntValueCallback;
import com.huawo.sdk.bluetoothsdk.interfaces.callback.QuickRepliesCallback;
import com.huawo.sdk.bluetoothsdk.interfaces.callback.RemoveBondCallback;
import com.huawo.sdk.bluetoothsdk.interfaces.callback.SetSocialAppsCallback;
import com.huawo.sdk.bluetoothsdk.interfaces.callback.SocialAppSwitchesCallback;
import com.huawo.sdk.bluetoothsdk.interfaces.callback.SocialAppsCallback;
import com.huawo.sdk.bluetoothsdk.interfaces.callback.StringListCallback;
import com.huawo.sdk.bluetoothsdk.interfaces.callback.StringValueCallback;
import com.huawo.sdk.bluetoothsdk.interfaces.callback.TimeFormatCallback;
import com.huawo.sdk.bluetoothsdk.interfaces.callback.TypedBaseInterfaceCallback;
import com.huawo.sdk.bluetoothsdk.interfaces.callback.WeatherUnitCallback;
import com.huawo.sdk.bluetoothsdk.interfaces.ops.SetElectronicCard;
import com.huawo.sdk.bluetoothsdk.interfaces.ops.models.Contact;
import com.huawo.sdk.bluetoothsdk.interfaces.ops.models.ElectronicCard;
import com.huawo.sdk.bluetoothsdk.interfaces.ops.models.QuickReply;
import com.huawo.sdk.bluetoothsdk.interfaces.ops.models.SocialApp;
import com.huawo.sdk.bluetoothsdk.interfaces.ops.models.SocialAppSwitch;
import com.huawo.sdk.bluetoothsdk.interfaces.ops.models.TimeFormat;
import com.huawo.sdk.bluetoothsdk.interfaces.ops.models.Unit;
import com.huawo.sdk.bluetoothsdk.interfaces.ops.models.UserInfo;
import com.huawo.sdk.bluetoothsdk.interfaces.ops.models.WeatherUnit;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import io.reactivex.Completable;
import io.reactivex.Observable;
import io.reactivex.Single;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import kotlin.io.FilesKt;

public class DeviceSDKProxy {
    /**
     * 命令超时时间（秒）
     */
    private static final String TAG = "DeviceSDKProxy";
    /**
     * 命令超时时间（秒）
     */
    private static final long CMD_TIMEOUT = 30;

    /**
     * 在每次调用SDK方法前判断蓝牙是否开启
     * 部分方法在蓝牙未开启时调用会导致应用崩溃
     *
     * @author YU
     */
    private static void requiredBluetoothEnabled() {
//        if (!BluetoothSDK.isBluetoothEnabled()) {
////            throw new SDKInvokeException(SDKInvokeException.CODE_BLUETOOTH_OFF, "The bluetooth service is disabled");
//        }
    }

    /**
     * 多次出现设备连接已断开，但应用还处于已连接的情况。
     * 目前通过在每次SDK调用报错时，如果错误码为9（BLUETOOTH_OFF）或13（DISCONNECTED），并且应用还处于连接状态，就直接更新应用状态
     *
     * @author YU
     */
//    private static void correctConnectState(int code) {
//        if (ErrorCode.BLUETOOTH_OFF == code || ErrorCode.DISCONNECTED == code) {
//            if (DeviceConnectManager.getConnectDevice() != null) {
//                Log.w("DeviceSDKProxy", "【连接状态校正】SDK出现断连错误，但应用还处于连接状态 -> 更新应用状态为未连接");
//                DeviceConnectManager.setConnectDevice(null);
//                disconnectWithoutClean();
//            }
//        }
//    }



    public static void init(Application sApplication){
        ApplicationHolder.sApplication = sApplication;
        BluetoothSDK.init(sApplication, 243);
        //初始化框架,调用一次即可,详细配置见#高级配置#
        SFSDK.getInstance().init(sApplication); //OTA表盘初始化
    }

    public static void disconnectWithoutClean() {
        BluetoothSDK.disconnectWithoutClean();
    }

    // ------------------设置个人信息------------------
    public static Completable setUserInfo(UserInfo userInfo) {
        return Completable.create(emitter -> {
            try {
                requiredBluetoothEnabled();
                BluetoothSDK.setUserInfo(userInfo, new BoolCallback() {
                    @Override
                    public void onSuccess() {
                        emitter.onComplete();
                    }

                    @Override
                    public void onFail(int code) {

                        emitter.onComplete();
                    }
                });
            } catch (Exception e) {
                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }

    // ------------------设置时间------------------
    public static Completable setDeviceTime(Date date) {
        return Completable.create(emitter -> {
            try {
                requiredBluetoothEnabled();
                BluetoothSDK.setDeviceTime(date, new BoolCallback() {
                    @Override
                    public void onSuccess() {
                        emitter.onComplete();
                    }

                    @Override
                    public void onFail(int code) {
                        emitter.onComplete();
                    }
                });
            } catch (Exception e) {
                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }

    // ------------------设置时间和时区------------------
    public static Completable setDeviceTimeStyle(Date date, Integer value) {
        return Completable.create(emitter -> {
            try {
                requiredBluetoothEnabled();
                BluetoothSDK.setDeviceTimeAndStyle(date, value, new BoolCallback() {
                    @Override
                    public void onSuccess() {
                        emitter.onComplete();
                    }

                    @Override
                    public void onFail(int code) {
                        emitter.onComplete();
                    }
                });
            } catch (Exception e) {
                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }

    // ------------------设置单位------------------
    public static Completable setUnit(Unit unit) {
        return Completable.create(emitter -> {
            try {
                requiredBluetoothEnabled();
                BluetoothSDK.setUnit(unit, new BoolCallback() {
                    @Override
                    public void onSuccess() {
                        emitter.onComplete();
                    }

                    @Override
                    public void onFail(int code) {
                        emitter.onComplete();
                    }
                });
            } catch (Exception e) {
                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }

    // ------------------设置语言------------------
    public static Completable setLanguage(String language) {
        return Completable.create(emitter -> {
            try {
                requiredBluetoothEnabled();
                BluetoothSDK.setLanguage(language, new BoolCallback() {
                    @Override
                    public void onSuccess() {
                        emitter.onComplete();
                    }

                    @Override
                    public void onFail(int code) {
                        emitter.onComplete();
                    }
                });
            } catch (Exception e) {
                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }

    // ------------------获取电量------------------
    public static Single<Integer> getBattery() {
        return Single.<Integer>create(emitter -> {
            try {
                requiredBluetoothEnabled();
                BluetoothSDK.getBattery(new IntValueCallback() {
                    @Override
                    public void onSuccess(int value) {
                        emitter.onSuccess(value);
                    }

                    @Override
                    public void onFail(int code) {
                        emitter.onSuccess(code);
                    }
                });
            } catch (Exception e) {
                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }

    // ------------------寻找手表------------------
    public static Completable findDevice() {
        return Completable.create(emitter -> {
            try {
//                requiredBluetoothEnabled();
                BluetoothSDK.findDevice(new BoolCallback() {
                    @Override
                    public void onSuccess() {
                        Log.e(TAG, "findDevice-------onSuccess");
                        emitter.onComplete();
                    }

                    @Override
                    public void onFail(int code) {
                        Log.e(TAG, "findDevice-------onFail");
                        emitter.onComplete();
                    }
                });
            } catch (Exception e) {
                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }

    public static Completable cancelConnect() {
        return Completable.create(emitter -> {
            try {
                requiredBluetoothEnabled();
                if (BluetoothSDK.isConnecting()) {
                    BluetoothSDK.disconnect(new DisconnectCallback() {
                        @Override
                        public void onSuccess() {
                            Log.e(TAG, "disconnect --- onSuccess");
                            emitter.onComplete();
                        }
                    });
                } else {
                    emitter.onComplete();
                }
            } catch (Exception e) {
                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }

    public static Completable bindAndPair() {
        return Completable.create(emitter -> {
            try {
                createPair().blockingAwait();
                bind().blockingAwait();
            } catch (Exception e) {

            }
        });
    }
    /**
     * 设备绑定流程
     */
    public static Completable bind() {
        return Completable.create(emitter -> {
            try {
                Log.i(TAG, "【设备绑定流程】获取锁...");
                if (!LOCK.tryLock(30, TimeUnit.SECONDS)) {

                }
                try {
                    Log.i(TAG, "【设备绑定流程】绑定...");
//                    final ConnectDevice connectDevice = DeviceConnectManager.getConnectDevice();
//                    if (connectDevice == null) {
//                        throw new IllegalStateException("No connected device was found.");
//                    }
//                    final BindDevice bindDevice = new BindDevice(
//                            Long.parseLong("0"),
//                            connectDevice.deviceId,
//                            connectDevice.deviceName,
//                            connectDevice.deviceType,
//                            connectDevice.device.getMac(),
//                            System.currentTimeMillis(),
//                            connectDevice.firmwareVersion
//                    );
//                    Log.i(TAG, "【设备绑定流程】绑定数据准备完成：" + bindDevice);
                    DeviceSDKProxy.startBind().timeout(30, TimeUnit.SECONDS).blockingAwait();
//                    DeviceEnvironmentManager.sync(true, true).timeout(30, TimeUnit.SECONDS).blockingAwait();
                    DeviceSDKProxy.endBind().timeout(30, TimeUnit.SECONDS).blockingAwait();

                    Log.i(TAG, "【设备绑定流程】绑定 -> 成功");
                    emitter.onComplete();
                } finally {
                    Log.i(TAG, "【设备绑定流程】释放锁...");
                    LOCK.unlock();
                }
            } catch (Exception e) {
                Log.i(TAG, "【设备绑定流程】绑定 -> 失败", e);
                emitter.onError(e);
            }
        });
    }

    public static Completable startBind() {
        return Completable.create(emitter -> {
            try {
                requiredBluetoothEnabled();
//                BluetoothSDK.startSifliBind(new BoolCallback() {//旧的需要绑定确认
                BluetoothSDK.startSifliBindWithoutConfirm(new BoolCallback() {
                    @Override
                    public void onSuccess() {
                        emitter.onComplete();
                    }

                    @Override
                    public void onFail(int code) {
                        emitter.onComplete();
                    }
                });

            } catch (Exception e) {

                emitter.onComplete();
            }
        }).subscribeOn(Schedulers.io());
    }

    public static Completable endBind() {
        return Completable.create(emitter -> {
            try {
                requiredBluetoothEnabled();
                BluetoothSDK.endBind(new BoolCallback() {
                    @Override
                    public void onSuccess() {
                        emitter.onComplete();
                    }

                    @Override
                    public void onFail(int code) {

                        emitter.onComplete();
                    }
                });
            } catch (Exception e) {

                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }

    /**
     * 设备解绑流程
     */
    public static Completable unbind(String macAddress) {
        return Completable.create(emitter -> {
            try {

                Log.i(TAG, "【设备解绑流程】取消正在进行的连接...");
                DeviceSDKProxy.cancelConnect().timeout(30, TimeUnit.SECONDS).onErrorComplete().blockingAwait();
                Log.i(TAG, "【设备解绑流程】获取锁...");
                if (!LOCK.tryLock(30, TimeUnit.SECONDS)) {
                    throw new Exception("The waiting time elapsed before the lock was acquired");
                }
                try {
                    Log.i(TAG, "【设备解绑流程】解绑...");

                    Log.i(TAG, "【设备解绑流程】删除本地绑定数据...");
                    Log.i(TAG, "【设备解绑流程】删除配对...");
                    removePair(macAddress).onErrorComplete().blockingAwait();
                    if (DeviceConnectManager.getConnectDevice() != null) {
                        Log.i(TAG, "【设备解绑流程】删除配对执行结束，应用仍处于连接状态，开始执行断连操作...");
                        disconnect().onErrorComplete().blockingAwait();
                    }
                    Log.i(TAG, "【设备解绑流程】异步删除服务器绑定数据...");
                    SM.spSaveString(sApplication, "MAC", "");
                    Log.i(TAG, "【设备解绑流程】解绑 -> 成功");
                    emitter.onComplete();
                } finally {
                    Log.i(TAG,"【设备解绑流程】释放锁...");
                    LOCK.unlock();
                }
            } catch (Exception e) {
                Log.i(TAG, "【设备解绑流程】解绑 -> 失败", e);
                emitter.onError(e);
            }
        });
    }
    private static final Lock LOCK = new ReentrantLock();
    /**
     * 设备断连流程
     */
    public static Completable disconnect() {
        return Completable.create(emitter -> {
            try {
                Log.i(TAG, "【设备断连流程】获取锁...");

                try {
                    Log.i(TAG, "【设备断连流程】断连...");
                    BluetoothSDK.disconnect(new DisconnectCallback() {
                        @Override
                        public void onSuccess() {
                            Log.e(TAG, "disconnect --- onSuccess");
                            emitter.onComplete();
                        }
                    });
                    Log.i(TAG, "【设备断连流程】断连 -> 成功");
                    emitter.onComplete();
                } finally {
                    Log.i(TAG, "【设备断连流程】释放锁...");
                }
            } catch (Exception e) {
                Log.i(TAG, "【设备断连流程】断连 -> 失败", e);
                emitter.onError(e);
            }
        });
    }

    /**
     * 删除配对流程（可能导致连接断开）
     */
    public static Completable removePair(String macAddress) {
        return Completable.create(emitter -> {
            try {
                Log.e(TAG, "【删除配对流程】删除配对...");
                Log.e(TAG, "【删除配对流程】断开设备BT连接...");

                Log.e(TAG, "【删除配对流程】断开应用与设备的连接...");
                DeviceSDKProxy.disconnectOnlyBt()
                        .timeout(15, TimeUnit.SECONDS)
                        .doOnComplete(() -> {
                            Log.e(TAG, "【删除配对流程】成功通知设备断开设备BT连接");
                        })
                        .doOnError(error -> {
                            Log.e(TAG, "【删除配对流程】通知设备断开BT连接失败", error);
                        })
                        .onErrorComplete().blockingAwait();

                if (DeviceSDKProxy.isBonded(macAddress)) {
                    Log.e(TAG, "【删除配对流程】删除本机配对信息...");
                    DeviceSDKProxy.removeBond(macAddress).timeout(20, TimeUnit.SECONDS).blockingAwait();
                    Log.e(TAG, "【删除配对流程】删除配对 -> 成功");
                } else {
                    Log.e(TAG, "【删除配对流程】删除配对 -> 跳过");
                }

                emitter.onComplete();
            } catch (Exception e) {
                Log.e(TAG, "【删除配对流程】删除配对 -> 失败", e);
                emitter.onError(e);
            }
        });
    }

    public static Completable disconnectOnlyBt() {
        return Completable.create(emitter -> {
            try {
                requiredBluetoothEnabled();
                BluetoothSDK.disconnectOnlyBt(new BoolCallback() {
                    @Override
                    public void onSuccess() {
                        emitter.onComplete();
                    }

                    @Override
                    public void onFail(int code) {
                        Log.e(TAG, "disconnectOnlyBt --- onFail " + code);
                        emitter.onComplete();
                    }
                });
            } catch (Exception e) {
                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }

    @SuppressLint("MissingPermission")
    public static Completable removeBond(@NonNull String macAddress) {
        return Completable.create(emitter -> {
            try {
                requiredBluetoothEnabled();
                BluetoothSDK.removeBond(macAddress, new RemoveBondCallback() {
                    @Override
                    public void onSuccess() {
                        emitter.onComplete();
                    }

                    @Override
                    public void onFail(int code) {
                        Log.e(TAG, "removeBond --- onFail " + code);
                        emitter.onComplete();
                    }
                });
            } catch (Exception e) {
                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }

    // ------------------天气------------------
    public static Completable setWeatherUnit(WeatherUnit weatherUnit) {
        return Completable.create(emitter -> {
            try {
                requiredBluetoothEnabled();
                BluetoothSDK.setWeatherUnit(weatherUnit, new BoolCallback() {
                    @Override
                    public void onSuccess() {
                        emitter.onComplete();
                    }

                    @Override
                    public void onFail(int code) {

                        emitter.onComplete();
                    }
                });
            } catch (Exception e) {

                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }

    public static Single<Integer> getWeatherUnit() {
        return Single.<Integer>create(emitter -> {
            try {
                requiredBluetoothEnabled();
                BluetoothSDK.getWeatherUnit(new WeatherUnitCallback() {
                    @Override
                    public void onFail(int i) {
                        emitter.onSuccess(i);
                    }

                    @Override
                    public void onSuccess(WeatherUnit weatherUnit) {
                        emitter.onSuccess(0);
                    }
                });
            } catch (Exception e) {

                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }


    public static Completable delWorkouts() {
        return Completable.create(emitter -> {
            try {
                requiredBluetoothEnabled();
                BluetoothSDK.delWorkouts(new BoolCallback() {
                    @Override
                    public void onSuccess() {
                        emitter.onComplete();
                    }

                    @Override
                    public void onFail(int code) {

                    }
                });
            } catch (Exception e) {

                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }

    // ------------------抬手亮屏------------------
    public static Single<Boolean> getFlipLightUpEnable() {
        return Single.<Boolean>create(emitter -> {
            try {
                requiredBluetoothEnabled();
                BluetoothSDK.getFlipLightUpEnable(new BoolValueCallback() {
                    @Override
                    public void onSuccess(boolean b) {
                        emitter.onSuccess(b);
                    }

                    @Override
                    public void onFail(int code) {

                        emitter.onSuccess(false);
                    }
                });
            } catch (Exception e) {

                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }

    public static Completable setFlipLightUpEnable(boolean value) {
        return Completable.create(emitter -> {
            try {
                requiredBluetoothEnabled();
                BluetoothSDK.setFlipLightUpEnable(value, new BoolCallback() {
                    @Override
                    public void onSuccess() {
                        emitter.onComplete();
                    }

                    @Override
                    public void onFail(int code) {

                        emitter.onComplete();
                    }
                });
            } catch (Exception e) {

                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }


    // ------------------快捷回复------------------

    public static Single<List<QuickReply>> getQuickReplies() {
        return Single.<List<QuickReply>>create(emitter -> {
            try {
                requiredBluetoothEnabled();
                BluetoothSDK.getQuickReplies(new QuickRepliesCallback() {
                    @Override
                    public void onSuccess(List<QuickReply> replyList) {
                        emitter.onSuccess(replyList != null ? replyList : Collections.emptyList());
                    }

                    @Override
                    public void onFail(int code) {

                        emitter.onSuccess(new ArrayList<>());
                    }
                });
            } catch (Exception e) {

                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }

    public static Completable editQuickReply(QuickReply quickReply) {
        return Completable.create(emitter -> {
            try {
                requiredBluetoothEnabled();
                BluetoothSDK.editQuickReply(quickReply, new BoolCallback() {
                    @Override
                    public void onSuccess() {
                        emitter.onComplete();
                    }

                    @Override
                    public void onFail(int code) {

                        emitter.onComplete();
                    }
                });
            } catch (Exception e) {

                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }
    // ------------------快捷回复------------------


    // ------------------心率------------------
    public static Single<Integer> getHeartrateMonitorInterval() {
        return Single.<Integer>create(emitter -> {
            try {
                requiredBluetoothEnabled();
                BluetoothSDK.getHeartrateMonitorInterval(new IntValueCallback() {
                    @Override
                    public void onSuccess(int value) {
                        emitter.onSuccess(value);
                    }

                    @Override
                    public void onFail(int code) {

                        emitter.onSuccess(0);
                    }
                });
            } catch (Exception e) {

                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }

    public static Completable setHeartrateMonitorInterval(int value) {
        return Completable.create(emitter -> {
            try {
                requiredBluetoothEnabled();
                BluetoothSDK.setHeartrateMonitorInterval(value, new BoolCallback() {
                    @Override
                    public void onSuccess() {
                        emitter.onComplete();
                    }

                    @Override
                    public void onFail(int code) {

                        emitter.onComplete();
                    }
                });
            } catch (Exception e) {

                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }

    // ------------------心率------------------


    // ------------------血氧------------------
    public static Completable startMeasureSpo2() {
        return Completable.create(emitter -> {
            try {
                requiredBluetoothEnabled();
                BluetoothSDK.startSpO2Monitoring(new BoolCallback() {
                    @Override
                    public void onSuccess() {
                        emitter.onComplete();
                    }

                    @Override
                    public void onFail(int code) {

                        emitter.onComplete();
                    }
                });
            } catch (Exception e) {

                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }

    public static Completable stopMeasureSpo2() {
        return Completable.create(emitter -> {
            try {
                requiredBluetoothEnabled();
                BluetoothSDK.stopSpO2Monitoring(new BoolCallback() {
                    @Override
                    public void onSuccess() {
                        emitter.onComplete();
                    }

                    @Override
                    public void onFail(int code) {

                        emitter.onComplete();
                    }
                });
            } catch (Exception e) {

                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }


    // ------------------SocialAppSwitch------------------
    public static Completable setSocialAppSwitch(SocialAppSwitch socialAppSwitch) {
        return Completable.create(emitter -> {
            try {
                requiredBluetoothEnabled();
                BluetoothSDK.setSocialAppSwitch(socialAppSwitch, new BoolCallback() {
                    @Override
                    public void onSuccess() {
                        emitter.onComplete();
                    }

                    @Override
                    public void onFail(int code) {

                        emitter.onComplete();
                    }
                });
            } catch (Exception e) {

                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }

    public static Single<List<SocialAppSwitch>> getSocialAppSwitches() {
        return Single.<List<SocialAppSwitch>>create(emitter -> {
            try {
                requiredBluetoothEnabled();
                BluetoothSDK.getSocialAppSwitches(new SocialAppSwitchesCallback() {
                    @Override
                    public void onSuccess(List<SocialAppSwitch> socialAppSwitchList) {
                        emitter.onSuccess(socialAppSwitchList != null ? socialAppSwitchList : Collections.emptyList());
                    }

                    @Override
                    public void onFail(int code) {

                        emitter.onSuccess(new ArrayList<>());
                    }
                });
            } catch (Exception e) {

                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }

    // ------------------推送APP------------------
    public static Single<List<SocialApp>> getSocialApps() {
        return Single.<List<SocialApp>>create(emitter -> {
            try {
                requiredBluetoothEnabled();
                BluetoothSDK.getSocialApps(new SocialAppsCallback() {
                    @Override
                    public void onSuccess(List<SocialApp> socialAppList) {
                        emitter.onSuccess(socialAppList != null ? socialAppList : Collections.emptyList());
                    }

                    @Override
                    public void onFail(int code) {

                        emitter.onSuccess(new ArrayList<>());
                    }
                });
            } catch (Exception e) {

                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }

    public static Observable<Float> setSocialApps(List<SocialApp> socialAppList) {
        return Observable.<Float>create(emitter -> {
            try {
                requiredBluetoothEnabled();
                BluetoothSDK.setSocialApps(socialAppList, new SetSocialAppsCallback() {
                    @Override
                    public void onReady() {
                    }

                    @Override
                    public void onUpload(float progress) {
                        emitter.onNext(progress);
                    }

                    @Override
                    public void onSuccess() {
                        emitter.onComplete();
                    }

                    @Override
                    public void onFail(int code) {

                        emitter.onComplete();
                    }
                });
            } catch (Exception e) {

                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }

    // ------------------亮屏时间------------------
    public static Single<Integer> getDisplayDuration() {
        return Single.<Integer>create(emitter -> {
            try {
                requiredBluetoothEnabled();
                BluetoothSDK.getDisplayDuration(new IntValueCallback() {
                    @Override
                    public void onSuccess(int value) {
                        emitter.onSuccess(value);
                    }

                    @Override
                    public void onFail(int code) {

                        emitter.onSuccess(0);
                    }
                });
            } catch (Exception e) {

                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }

    public static Completable setDisplayDuration(int value) {
        return Completable.create(emitter -> {
            try {
                requiredBluetoothEnabled();
                BluetoothSDK.setDisplayDuration(value, new BoolCallback() {
                    @Override
                    public void onSuccess() {
                        emitter.onComplete();
                    }

                    @Override
                    public void onFail(int code) {

                        emitter.onComplete();
                    }
                });
            } catch (Exception e) {

                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }

    // ------------------时间格式------------------
    public static Single<Integer> getTimeFormat() {
        return Single.<Integer>create(emitter -> {
            try {
                requiredBluetoothEnabled();
                BluetoothSDK.getTimeFormat(new TimeFormatCallback() {
                    @Override
                    public void onSuccess(TimeFormat timeFormat) {
                        if (timeFormat != null) {
                            emitter.onSuccess(timeFormat.getValue());
                        } else {
                            emitter.onSuccess(1);
                        }
                    }

                    @Override
                    public void onFail(int code) {

                        emitter.onSuccess(0);
                    }
                });
            } catch (Exception e) {

                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }

    public static Completable setTimeFormat(int value) {
        return Completable.create(emitter -> {
            try {
                requiredBluetoothEnabled();
                BluetoothSDK.setTimeFormat(TimeFormat.valueOf(value), new BoolCallback() {
                    @Override
                    public void onSuccess() {
                        emitter.onComplete();
                    }

                    @Override
                    public void onFail(int code) {

                        emitter.onComplete();
                    }
                });
            } catch (Exception e) {

                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }

    // ------------------设置在线表盘------------------
    public static Observable<Integer> setOnlineWatchface(byte[] file, String fileName) {
        return Observable.<Integer>create(emitter -> {
            try {
                requiredBluetoothEnabled();
                File zipPath = new File(fileName);
                FilesKt.writeBytes(zipPath, file);
                QjsWatchface qjsWatchface = new QjsWatchface(zipPath.getPath(), sApplication);
                qjsWatchface.syncOnlineZip(SM.spLoadStringno(sApplication, "MAC"), new QjsWatchfaceCallback() {
                    @Override
                    public void onReady() {
                    }

                    @Override
                    public void onProccess(int progress) {
                        emitter.onNext(progress);
                    }

                    @Override
                    public void onSuccess() {
                        emitter.onComplete();
                        zipPath.delete();
                    }

                    @Override
                    public void onFail(int code) {

                        emitter.onComplete();
                    }
                });
            } catch (Exception e) {

                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }

    // ------------------上传联系人------------------
    public static Completable uploadContacts(List<Contact> contactList) {
        return Completable.create(emitter -> {
            try {
                requiredBluetoothEnabled();
                BluetoothSDK.setContacts(contactList, new BoolCallback() {
                    @Override
                    public void onSuccess() {
                        emitter.onComplete();
                    }

                    @Override
                    public void onFail(int code) {

                        emitter.onComplete();
                    }
                });
            } catch (Exception e) {

                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }

    // ------------------获取电子卡------------------
    public static Single<List<ElectronicCard>> getAllElectronicCard() {
        return Single.<List<ElectronicCard>>create(emitter -> {
            try {
                requiredBluetoothEnabled();
                BluetoothSDK.getAllElectronicCard(new TypedBaseInterfaceCallback<List<ElectronicCard>>() {
                    @Override
                    public void onSuccess(List<ElectronicCard> value) {
                        emitter.onSuccess(value);
                    }

                    @Override
                    public void onFail(int code) {

                        emitter.onSuccess(new ArrayList<>());
                    }
                });
            } catch (Exception e) {

                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }

    public static Single<String> getElectronicCardValue(int id) {
        return Single.<String>create(emitter -> {
            try {
                requiredBluetoothEnabled();
                BluetoothSDK.getElectronicCardValue(id, new TypedBaseInterfaceCallback<String>() {
                    @Override
                    public void onSuccess(String value) {
                        emitter.onSuccess(value);
                    }

                    @Override
                    public void onFail(int code) {

                        emitter.onSuccess("");
                    }
                });
            } catch (Exception e) {

                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }

    public static Completable setElectronicCard(SetElectronicCard.SetElectronicCardParam param) {
        return Completable.create(emitter -> {
            try {
                requiredBluetoothEnabled();
                BluetoothSDK.setElectronicCard(param, new BoolCallback() {
                    @Override
                    public void onSuccess() {
                        emitter.onComplete();
                    }

                    @Override
                    public void onFail(int code) {

                        Log.e(TAG,"errorCode + " + code );
                        emitter.setDisposable(new Disposable() {
                            @Override
                            public void dispose() {

                            }

                            @Override
                            public boolean isDisposed() {
                                return false;
                            }
                        });
                    }
                });
            } catch (Exception e) {

                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }


    public static Single<ConnectDevice> getConnectDevice() {
        return Single.<ConnectDevice>create(emitter -> {
            try {
                requiredBluetoothEnabled();
                Device device = BluetoothSDK.getConnectedDevice();
                if (device == null) {
                    Log.e("getConnectDevice","空设备");
                    emitter.onSuccess(new ConnectDevice(null,"","","","",0));
                    return;
                }
                String deviceType = Single.<String>create(iemitter -> {
                    BluetoothSDK.getDeviceType(new StringValueCallback() {
                        @Override
                        public void onSuccess(String value) {
                            iemitter.onSuccess(value);
                        }

                        @Override
                        public void onFail(int code) {

                            iemitter.onSuccess("");
                        }
                    });
                }).blockingGet();
                String firmwareVersion = Single.<String>create(iemitter -> {
                    BluetoothSDK.getFirmwareVersion(new StringValueCallback() {
                        @Override
                        public void onSuccess(String value) {
                            iemitter.onSuccess(value);
                        }

                        @Override
                        public void onFail(int code) {

                            iemitter.onSuccess("");
                        }
                    });
                }).blockingGet();

                boolean ifOk = !(TextUtils.isEmpty(firmwareVersion) || TextUtils.isEmpty(deviceType) || TextUtils.isEmpty(FirmwareVersionUtils.extractV(firmwareVersion)) || (firmwareVersion.equals(deviceType)));

                if (ifOk) {
                    ConnectDevice connectDevice = new ConnectDevice(device, device.getMac(), deviceType, device.getName(), firmwareVersion, System.currentTimeMillis());
                    emitter.onSuccess(connectDevice);
                    return;
                } else {
                    emitter.onSuccess(new ConnectDevice(null,"","","","",0));
                    return;
                }
            } catch (Exception e) {

                Log.e("getConnectDevice",e.toString());
                emitter.onSuccess(new ConnectDevice(null,"","","","",0));
//                emitter.onSuccess(null);
            }
        }).subscribeOn(Schedulers.io());
    }

    public static Single<FirmwareVersionDate> getFirmwareVersionDate() {
        return Single.<FirmwareVersionDate>create(emitter -> {
            ConnectDevice connectDevice = null;
            VersionBean versionBean =null;
            try{
                connectDevice = DeviceSDKProxy.getConnectDevice().timeout(60, TimeUnit.SECONDS).blockingGet();
//                versionBean = DeviceSDKProxy.getVersionUpdate(connectDevice).blockingGet();
            }catch (Exception e ){
                //查询不到数据就返回空
                emitter.onSuccess(new FirmwareVersionDate());
                return;
            }
            //查询不到数据就返回空
            if(connectDevice == null  || versionBean == null){
                emitter.onSuccess(new FirmwareVersionDate());
                return;
            }else if(connectDevice.firmwareVersion.equals("")){
                emitter.onSuccess(new FirmwareVersionDate());
                return;
            }
            try {
                FirmwareVersionDate firmwareVersionDate = new FirmwareVersionDate();
                firmwareVersionDate.setOld_version(FirmwareVersionUtils.extractV(connectDevice.firmwareVersion) + "B" + FirmwareVersionUtils.extractB(connectDevice.firmwareVersion));
                DeviceUpgradeManager.setDeviceUpgradeInfo(null);
                if (versionBean.getCode() == 0 && versionBean.getData() != null) {
                    DeviceUpgradeManager.setDeviceUpgradeInfo(versionBean.getData());
                    firmwareVersionDate.setUpdateStatus(0);
                    firmwareVersionDate.setOld_version(versionBean.getData().version + "B" + versionBean.getData().build);
                    emitter.onSuccess(firmwareVersionDate);
                } else if (versionBean.getCode() == 0 && versionBean.getData() == null) {
                    firmwareVersionDate.setUpdateStatus(1);
                    emitter.onSuccess(firmwareVersionDate);
                } else {
                    firmwareVersionDate.setUpdateStatus(2);
                    emitter.onSuccess(firmwareVersionDate);
                }
            }catch (Exception e){
                emitter.onSuccess(new FirmwareVersionDate());
                return;
            }


        }).subscribeOn(Schedulers.io());
    }

//    public static Single<VersionBean> getVersionUpdate(ConnectDevice connectDevice) {
//        return Single.<VersionBean>create(emitter -> {
//            try {
//                String url = "https://test.huawo-wear.com/api/v1/devices/upgrades";
//                JSONObject jsonObject = new JSONObject();
//                jsonObject.put("currentBuild", FirmwareVersionUtils.extractB(connectDevice.firmwareVersion));
//                jsonObject.put("productCode", connectDevice.deviceType);
//                jsonObject.put("customerCode", "HaWoFit");
//                jsonObject.put("currentVersion", FirmwareVersionUtils.extractV(connectDevice.firmwareVersion));
//                //使用原始回调
//                QSHttp.post(url)
//                        .header("appVersion", "1.0.0")
//                        .header("appId", "com.huawo.sdk")
//                        .jsonBody(jsonObject)
//                        .buildAndExecute(new HttpCallback() {
//                            @Override
//                            public void onSuccess(ResponseParams response) {
//                                String str = response.string();
//                                VersionBean versionBean = new Gson().fromJson(str, VersionBean.class);
//                                emitter.onSuccess(versionBean);
//                            }
//
//                            @Override
//                            public void onFailure(HttpException e) {
//                                emitter.onSuccess(new VersionBean());
//                            }
//                        });
//            } catch (Exception e) {
//
//                emitter.onError(e);
//            }
//        }).subscribeOn(Schedulers.io());
//    }

    // 获取当前连接的设备
    public static Single<ConnectDevice> getConnectDeviceNew() {
        return DeviceSDKProxy.getConnectDevice()
                .doOnSuccess(connectDevice -> {
                    try {
                    } catch (Exception e) {
                    }
                });
    }

    public static void SyncCustomWatchFace(Context context, QjsWatchFaceBean qjsWatchFaceBean, OnWatchFaceTransListener watchFaceTransListener) {

        if (qjsWatchFaceBean == null || (qjsWatchFaceBean.background == null && qjsWatchFaceBean.gif == null)) {
            Log.e("SyncCustomWatchFace","background and gid not null");
            return;
        }
        Bitmap bg = ImageUtils.drawableToBitmap(getDrawable(context, R.drawable.device_ui_module_customize_hr04_default_bg));
        Bitmap finalBg = ImageUtils.getNewBitmap(bg, qjsWatchFaceBean.width, qjsWatchFaceBean.heigh);
        Bitmap finalThumbnail = ImageUtils.getNewBitmap(bg, qjsWatchFaceBean.width, qjsWatchFaceBean.heigh);
        QjsWatchface qjsWatchface = new QjsWatchface(context, qjsWatchFaceBean.width, qjsWatchFaceBean.heigh, qjsWatchFaceBean.index);

        //背景图片
        if (qjsWatchFaceBean.background == null) {
            qjsWatchface.setBackground(finalBg);
        } else {
            finalBg = ImageUtils.getNewBitmap(qjsWatchFaceBean.background, qjsWatchFaceBean.width, qjsWatchFaceBean.heigh);
            qjsWatchface.setBackground(finalBg);
        }

        //缩略图
        if (qjsWatchFaceBean.thumbnail == null) {
            qjsWatchface.setThumbnail(finalThumbnail);
        } else {
            qjsWatchface.setThumbnail(ImageUtils.getCircleBitmap(ImageUtils.zoomBitmap(qjsWatchFaceBean.thumbnail, qjsWatchFaceBean.width, qjsWatchFaceBean.heigh)));
        }

        //动态图片
        if (qjsWatchFaceBean.gif != null) {
            Bitmap bitmap = BitmapFactory.decodeFile(qjsWatchFaceBean.gif.getAbsolutePath());
            qjsWatchface.setBackground(ImageUtils.zoomBitmap(bitmap, qjsWatchFaceBean.width, qjsWatchFaceBean.heigh));
            qjsWatchface.setThumbnail(ImageUtils.getCircleBitmap(ImageUtils.zoomBitmap(bitmap, qjsWatchFaceBean.width, qjsWatchFaceBean.heigh)));
            qjsWatchface.setGifFile(qjsWatchFaceBean.gif.getAbsolutePath());
        }

        //设置样式
        qjsWatchface.setStyle(qjsWatchFaceBean.currentDirection);

        //添加控件
//        List<QjsWidget> widgetList = new ArrayList<>();
//        if(qjsWatchFaceBean.currentDirection == 0){
//            widgetList.add(new QjsTime("time", qjsWatchFaceBean.color, qjsWatchFaceBean.width, qjsWatchFaceBean.heigh));
//            widgetList.add(new QjsStep("step", qjsWatchFaceBean.color));
//            widgetList.add(new QjsCalorie("cal",qjsWatchFaceBean.color));
//            widgetList.add(new QjsHeartrate("hr", qjsWatchFaceBean.color));
//        }

        qjsWatchface.setWidgetList(qjsWatchFaceBean.widgetList);

        qjsWatchface.syncToWatch(SM.spLoadStringno(sApplication, "MAC"), new QjsWatchfaceCallback() {

            @Override
            public void onReady() {
                watchFaceTransListener.onTransProgressStarting();
            }

            @Override
            public void onProccess(int progress) {
                watchFaceTransListener.onTransProgressChanged(progress);
            }

            @Override
            public void onSuccess() {
                watchFaceTransListener.onTransCompleted();
            }

            @Override
            public void onFail(int code) {
                if (code == 37) {
                    watchFaceTransListener.onTransError(2, "空间不足");
                } else if (code == 38 || code == 6 || code == 1 || code == 4) {
                    watchFaceTransListener.onTransError(1, "蓝牙断链或同步超时");
                } else {
                    watchFaceTransListener.onTransError(3, "其他功能运行中");
                }

            }
        });
    }

    // ------------------蓝牙配对------------------
    public static boolean isBonded() {
        return BluetoothSDK.isBonded();
    }

    public static boolean isBonded(String macAddress) {
        return BluetoothSDK.isBonded(macAddress);
    }

    public static Completable createBond() {
        return Completable.create(emitter -> {
            try {
                requiredBluetoothEnabled();
                BluetoothSDK.createBond(new CreateBondCallback() {
                    @Override
                    public void onSuccess() {
                        emitter.onComplete();
                    }

                    @Override
                    public void onFail(int code) {

                        emitter.onComplete();
                    }
                });
            } catch (Exception e) {

                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }

    public static Completable setBTSwitch(boolean value) {
        return Completable.create(emitter -> {
            try {
                requiredBluetoothEnabled();
                BluetoothSDK.setBTSwitch(value, new BoolCallback() {
                    @Override
                    public void onSuccess() {
                        emitter.onComplete();
                    }

                    @Override
                    public void onFail(int code) {

                        emitter.onComplete();
                    }
                });
            } catch (Exception e) {

                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }

    public static Completable turnOnBTSwitchWithOption(boolean autoConnect) {
        return Completable.create(emitter -> {
            try {
                requiredBluetoothEnabled();
                BluetoothSDK.turnOnBTSwitchWithOption(autoConnect, new BoolCallback() {
                    @Override
                    public void onSuccess() {
                        emitter.onComplete();
                    }

                    @Override
                    public void onFail(int code) {

                        emitter.onComplete();
                    }
                });
            } catch (Exception e) {

                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }

    /**
     * 创建配对流程
     */
    public static Completable createPair() {
        return Completable.create(emitter -> {
            try {
                Log.e(TAG, "【创建配对流程】创建配对...");
                if (DeviceSDKProxy.isBonded()) {
                    Log.e(TAG, "【创建配对流程】打开BT（已绑定）...");
//                    DeviceSDKProxy.connectProfiles();
                    DeviceSDKProxy.turnOnBTSwitchWithOption(true)
                            .timeout(30, TimeUnit.SECONDS)
                            .doOnComplete(() -> {
                                Log.e(TAG, "【创建配对流程】打开BT成功");
                            })
                            .doOnError(error -> {
                                Log.e(TAG, "【创建配对流程】打开BT失败", error);
                            })
                            .onErrorComplete().blockingAwait();
                } else {
                    Log.e(TAG, "【创建配对流程】打开BT（未绑定）...");
                    DeviceSDKProxy.setBTSwitch(true)
                            .timeout(30, TimeUnit.SECONDS)
                            .doOnComplete(() -> {
                                Log.e(TAG, "【创建配对流程】打开BT成功");
                            })
                            .doOnError(error -> {
                                Log.e(TAG, "【创建配对流程】打开BT失败", error);
                            })
                            .onErrorComplete().blockingAwait();
                    Thread.sleep(3000);// 延迟等待设备BT打开完成
                    Log.e(TAG, "【创建配对流程】开始配对...");
                    DeviceSDKProxy.createBond().timeout(30, TimeUnit.SECONDS).blockingAwait();
                    Log.e(TAG, "【创建配对流程】创建配对 -> 成功");
                }
                emitter.onComplete();
            } catch (Exception e) {
                Log.e(TAG, "【创建配对流程】创建配对 -> 失败", e);
                emitter.onError(e);
            }
        });
    }

    public static Single<String> getSilfiCurrentWatchface() {
        return Single.<String>create(emitter -> {
            try {
                requiredBluetoothEnabled();
                BluetoothSDK.getSifliCurrentWatchface(new StringValueCallback() {
                    @Override
                    public void onSuccess(String value) {
                        emitter.onSuccess(TextUtils.isEmpty(value) ? "" : value.trim());
                    }

                    @Override
                    public void onFail(int code) {
                        emitter.onSuccess("");
                    }
                });
            } catch (Exception e) {

                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }

    public static Single<List<String>> getSifliCurrentWatchface() {
        return Single.<List<String>>create(emitter -> {
            try {
                requiredBluetoothEnabled();
                BluetoothSDK.getSifliWatchfaces(new StringListCallback() {
                    @Override
                    public void onSuccess(List<String> valueList) {
                        emitter.onSuccess(valueList);
                    }

                    @Override
                    public void onFail(int code) {
                        emitter.onSuccess(new ArrayList<>());
                    }
                });
            } catch (Exception e) {

                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }

    public static Completable switchSilfiWatchfaceBy(String name) {
        return Completable.create(emitter -> {
            try {
                requiredBluetoothEnabled();
                BluetoothSDK.switchSifliWatchfaceBy(name, new BoolCallback() {
                    @Override
                    public void onSuccess() {
                        emitter.onComplete();
                    }

                    @Override
                    public void onFail(int code) {
                        emitter.onComplete();
                    }
                });
            } catch (Exception e) {

                emitter.onError(e);
            }
        }).subscribeOn(Schedulers.io());
    }



}